package com.ruoyi.business.controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.business.domain.BusPerson;
import com.ruoyi.business.domain.dto.DateDto;
import com.ruoyi.business.domain.vo.PeopleRegisterVo;
import com.ruoyi.business.service.IBusPersonService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DataMask;
import com.ruoyi.common.utils.ServletUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 人员台账Controller
 * 
 * @author ling
 * @date 2024-07-10
 */
@RestController
@RequestMapping("/business/person")
public class BusPersonController extends BaseController
{
    @Autowired
    private IBusPersonService busPersonService;
    @Value("${export.max:10000}")
    private Integer max;

    @Resource
    private TokenService tokenService;

    /**
     * 查询人员台账列表
     */
    @PreAuthorize("@ss.hasPermi('business:person:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusPerson busPerson)
    {
        startPage();
        List<BusPerson> list = busPersonService.selectBusPersonList(busPerson);
        // 遍历集合list
        for ( BusPerson busPeople: list
             ) {
            String phoneNum = DataMask.maskPhoneNumber(busPeople.getPersonPhone());
//            System.out.println(phoneNum);
            busPeople.setPersonPhone(phoneNum);
        }

        //  对电话号码进行脱敏
//        list.stream().forEach(b ->b.setPersonPhone(DataMask.maskPhoneNumber(busPerson.getPersonPhone())));
//      list.forEach(System.out::println);
        return getDataTable(list);
    }



    /**
     * 导出人员台账列表
     */
    @PreAuthorize("@ss.hasPermi('business:person:export')")
    @Log(title = "人员台账", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusPerson busPerson)
    {

        // 选择单条数据、所有查询结果的导出
//        System.out.println("导出人员台账： "+ busPerson);
        List<BusPerson> list = busPersonService.selectBusPersonList(busPerson);

//        list.forEach(System.out::println);
        if (list.size() > max) {
            throw new ServiceException("导出失败！,每次最多导出 " + max + "条");
        }

        ExcelUtil<BusPerson> util = new ExcelUtil<BusPerson>(BusPerson.class);
        util.exportExcel(response, list, "人员台账数据");
    }

    /**
     * 获取人员台账详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:person:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(busPersonService.selectBusPersonById(id));
    }

    /**
     * 新增人员台账
     */
    @PreAuthorize("@ss.hasPermi('business:person:add')")
    @Log(title = "人员台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusPerson busPerson)
    {
        return toAjax(busPersonService.insertBusPerson(busPerson));
    }

    /**
     * 修改人员台账
     */
    @PreAuthorize("@ss.hasPermi('business:person:edit')")
    @Log(title = "人员台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusPerson busPerson)
    {
        return toAjax(busPersonService.updateBusPerson(busPerson));
    }

    /**
     * 删除人员台账
     */
    @PreAuthorize("@ss.hasPermi('business:person:remove')")
    @Log(title = "人员台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(busPersonService.deleteBusPersonByIds(ids));
    }

    /**
     * 功能描述：查看一段时间的用户注册量
     *
     * @param beginDate
     * @param endDate
     * @return {@link R }<{@link PeopleRegisterVo }>
     * @author ling
     * @date 2024/08/05 09:43
     */
    @Anonymous
    @Log(title = "用户注册量", businessType = BusinessType.OTHER)
    @GetMapping("/peonumlist")
    public R<PeopleRegisterVo> CountPeoRes( @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginDate, @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate){
        logger.info("时间：{},{}",beginDate,endDate);
//        logger.info("时间：{}",date);
        return R.ok( busPersonService.getTableData(beginDate,endDate));
//        return null;
    }

    /**
     * 导入数据
     *
     * @param file          文件
     * @param updateSupport 是否更新已存在的用户数据
     * @return {@link AjaxResult }
     * @throws Exception 异常
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BusPerson> util = new ExcelUtil<>(BusPerson.class);
        List<BusPerson> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();

        String message = busPersonService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 导出模板
     *
     * @return {@link AjaxResult }
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<BusPerson> util = new ExcelUtil<BusPerson>(BusPerson.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据id查询班组人员信息
     *
     * @param teamId 班组id
     * @return {@link AjaxResult }
     */
    @Anonymous
    @PostMapping("/{teamId}")
    public AjaxResult getTeamPerson(@PathVariable Long teamId)
    {
//        查村对应班组员工
        List<BusPerson> list = busPersonService.getPersonListByTeamId(teamId);
        return AjaxResult.success(list);
    }

    /**
     *  根据岗位id查询人员列表
     *
     * @param postId  岗位Id
     * @return {@link AjaxResult }
     */
    @Anonymous
    @PostMapping("/getPersonList/{postId}")
    public AjaxResult getPostPersonList(@PathVariable Long postId){
        List<BusPerson> list = busPersonService.getPostPersonListByPostId(postId);
        return AjaxResult.success(list);
    }


}
